package com.hundsun.yr.universal.p2p.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.common.MD5Utils;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.utils.HsDateUtils;
import com.hundsun.yr.universal.library.utils.HsNumberUtils;
import com.hundsun.yr.universal.library.utils.HsStringUtils;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.utils.RegularUtils;
import com.hundsun.yr.universal.library.widget.HSEditText;
import com.hundsun.yr.universal.library.widget.HSEditText.HSInputType;
import com.hundsun.yr.universal.library.widget.HSPassedwordEditText;
import com.hundsun.yr.universal.library.widget.HSSipEditText;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.ui.activity.LoginActivity;
import com.hundsun.yr.universal.p2p.widget.ItemView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * 工具类
 *
 * @author tonglj
 */
public class CommTool {
    private static final int MIN_DELAY_TIME = 1500;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;

    /**
     * 根据输入的密码字串， 返回对应的密码强度值
     *
     * @param pwdstring 输入的密码字串
     * @param type      0：全部是数字便认为是弱密码 1：全部是数字也不认为是弱密码
     * @return 计算出的密码强度值 1：弱密码
     * @author 代码整理自p2p1。0
     */
    public static double getPasswordStrength(String pwdstring, int type) {
        double result = 0;
        int i = 0;
        int type1 = 0;
        int type2 = 0;
        int type3 = 0;
        int basenu = 0;

        int pwdlen = pwdstring.length();

        for (i = 0; i < pwdlen; i++) {
            char c = pwdstring.charAt(i);

            if (c >= '0' && c <= '9') {
                type1 = 10;

            } else if (c >= 'a' && c <= 'z') {
                type2 = 26;
            } else if (c >= 'A' && c <= 'Z') {
                type2 = 26;
            } else {
                type3 = 37;
            }
        }

        basenu = type1 + type2 + type3;

        double nnu = Math.pow(basenu, pwdlen);
        result = Math.log10(nnu);

        if (type == 0) {
            if (basenu == 10) {
                result = 1;
            }
        }

        return result;
    }

    /**
     * 给数字最大保留两位小数
     *
     * @param num
     * @return
     */
    public static String setMaxDigits(BigDecimal num) {
        num = num.setScale(2, BigDecimal.ROUND_DOWN);//截取后两位
        String result = num.toString();
        return HsNumberUtils.setMaxDigits(MathUtils.string2double(result), 2);
    }

    /**
     * 始终保留两位小数
     *
     * @param num
     * @return
     */
    public static String keep2Digits(BigDecimal num) {
        num = num.setScale(2, BigDecimal.ROUND_DOWN);//截取后两位
        String res = num.toString();
        if (res.length() - 2 == res.lastIndexOf('.') && res.lastIndexOf('.') != -1) {
            res = res + "0";
        }
        return res;
    }

    /**
     * 始终保留一位小数
     *
     * @param num
     * @return
     */
    public static String keep1Digits(BigDecimal num) {
        num = num.setScale(1, BigDecimal.ROUND_DOWN);//截取后两位
        String res = num.toString();
        if (res.length() - 1 == res.lastIndexOf('.') && res.lastIndexOf('.') != -1) {
            res = res + "0";
        }
        return res;
    }

    /**
     * 保留一位有效数字
     *
     * @param num
     * @return
     */
    public static String keep1Digits(String num) {
        DecimalFormat df = new DecimalFormat("######0.0");
        try {
            return df.format(Double.valueOf(num));
        } catch (Exception e) {
            return "0.00";
        }
    }

    public static String keep2Digits(String num) {
        DecimalFormat df = new DecimalFormat("######0.00");
        try {
            return df.format(Double.valueOf(num));
        } catch (Exception e) {
            return "0.00";
        }
    }

    /**
     * 给数字最大保留两位小数
     *
     * @param num
     * @return
     */
    public static String setMaxDigits(double num) {
        return setMaxDigits(MathUtils.getBigDecimal(num + ""));
    }

    /**
     * 金额单位转换（大于10万进行转换）格式化
     *
     * @return
     */
    public static String roundingAmount(double money) {
        return HsNumberUtils.roundingAmount(money, false);
    }

    /**
     * 金额单位转换（大于10万进行转换）
     *
     * @return
     */
    public static String roundingAmount(BigDecimal money) {
        return HsNumberUtils.roundingAmount(money, false);
    }

    /**
     * string[]转ArrayList
     *
     * @param arr
     * @return
     */
    public static List<String> arr2ArrList(String[] arr) {
        List<String> list = Arrays.asList(arr);
        return list;
    }

    /**
     * 获取控件的text函数
     *
     * @param view
     * @return
     */
    public static String getValue(View view) {
        String text = "";
        if (view instanceof HSPassedwordEditText) {
            text = ((HSPassedwordEditText) view).getText();
        } else if (view instanceof HSEditText) {
            HSEditText hsedit = (HSEditText) view;
            HSInputType inputType = hsedit.getHSInputType();
            if (inputType == HSInputType.PHONE) {
                text = hsedit.getPhone();
            } else if (inputType == HSInputType.BANKCARD) {
                text = hsedit.getBank();
            } else {
                text = hsedit.getText().toString();
            }
        } else if (view instanceof TextView) {
            text = ((TextView) view).getText().toString();
        } else if (view instanceof ItemView) {
            text = ((ItemView) view).getRealValue();
        } else if (view instanceof HSSipEditText) {
            text = ((HSSipEditText) view).getText();
            // 如果有遗漏可在此添加
        }
        return text;
    }

    /**
     * 控件设置值
     *
     * @param view
     * @param value
     */
    public static void setValue(View view, String value) {
        if (view instanceof TextView) {
            ((TextView) view).setText(value);
        } else if (view instanceof ItemView) {
            ((ItemView) view).setValue(value);
        }
    }

    /**
     * encodPhone("15787041234") = 157****1234
     *
     * @param phone
     * @return
     */
    public static String encodPhone(String phone) {
        try {
            return HsStringUtils.abbreviate(phone, "*******", 2, 9);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * encodPhone("15787041234") = 157****1234
     *
     * @param phone
     * @return
     */
    public static String encodPhone(String phone, String code) {
        try {
            return HsStringUtils.abbreviate(phone, code, 3, 11);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 加密银行卡号
     *
     * @param banknum
     * @return
     */
    public static String encodBankNum(String banknum) {
        try {
            return HsStringUtils.abbreviate(banknum, "*****", 4, banknum.length() - 4);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 加密身份证号
     *
     * @param
     * @return
     */
    public static String encodCertNo(String certno) {
        try {
            return HsStringUtils.abbreviate(certno, "********", 3, certno.length() - 4).toUpperCase();
        } catch (Exception e) {
            return "";
        }
    }

    public static String encodName(String name) {
        try {
            return HsStringUtils.abbreviate(name, "**", 0, name.length() - 1);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 加密数字
     *
     * @param certno
     * @return
     */
    public static String encodNum(String certno) {
        try {
            return HsStringUtils.abbreviate(certno, "*****", 0, certno.length());
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 验证码位数校验
     *
     * @param verification
     * @return
     */
    public static boolean checkVerificateCode(String verification) {
        if (verification == null) {
            return false;
        }// 6位且是数字
        return verification.length() == 6 && HsStringUtils.isNumeric(verification);
    }

    /**
     * 密码正确性校验（6-16数字或密码）
     *
     * @param passStr
     * @return
     */
    public static boolean checkPwd(String passStr) {
        return RegularUtils.regular(RegularUtils.REGEX_PWD, passStr);
    }

    /**
     * 是否设置了交易密码
     *
     * @param sp 保存在sharedPrifance
     * @return
     */
    public static boolean ifPayPwd(HSSharedPreferences sp) {
        return TextUtils.equals(sp.getShareProf(UserInfo.IF_PAYPWD), "YES");
    }


    /**
     * 交易密码正确性校验
     *
     * @param passStr
     * @return
     */
    public static boolean checkPayPwd(String passStr) {
        if (passStr == null) {
            return false;
        }// 6位且是数字
        return passStr.length() == 6 && HsStringUtils.isNumeric(passStr);
    }

    /**
     * 手机号校验
     *
     * @param phone
     * @return
     */
    public static boolean checkMobile(String phone) {
        return RegularUtils.isPhoneNum(phone);
    }

    /**
     * 获取资源库中string数组
     *
     * @param context
     * @param id
     * @return
     */
    public static String[] getResStrArray(Context context, int id) {
        return context.getResources().getStringArray(id);
    }

    /**
     * 获取资源库中string数组并转为ArrayList
     *
     * @param context
     * @param id
     * @return
     */
    public static List<String> getResStrList(Context context, int id) {
        return arr2ArrList(getResStrArray(context, id));
    }

    /**
     * 获取资源库中int数组并转为ArrayList
     *
     * @param context
     * @param id
     * @return
     */
    @SuppressLint("Recycle")
    public static ArrayList<Integer> getResIntList(Context context, int id) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        TypedArray types = context.getResources().obtainTypedArray(id);
        int count = getResStrArray(context, id).length;
        for (int i = 0; i < count; i++) {
            list.add(types.getResourceId(i, 0));
        }
        return list;
    }

    /**
     * 数值转化
     *
     * @param intstring
     * @param defaultvalue
     * @return
     */
    public static int parseInt(String intstring, int defaultvalue) {
        try {
            return Integer.parseInt(intstring);
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return defaultvalue;
    }

    /**
     * 百分比数值保留两位小数
     *
     * @param
     * @param
     * @return
     */
    public static String formartPercent(double value) {
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(2);
        return format.format(value) + "%";
    }

    /**
     * 百分比数值保留一位小数
     *
     * @param
     * @param
     * @return
     */
    public static String formartPercent1(double value) {
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(1);
        format.setMinimumFractionDigits(1);
        return format.format(value) + "%";
    }

    /**
     * 百分比数值保留两位小数
     *
     * @param
     * @param
     * @return
     */
    public static String formart1(double value) {
        DecimalFormat formater = new DecimalFormat();
        formater.setMaximumFractionDigits(2);
        formater.setMinimumFractionDigits(1);
        formater.setRoundingMode(RoundingMode.FLOOR);
        return formater.format(value).replace(",", "") + "%";
    }

    /**
     * 把flag的 yes，no状态转为boolean类型
     *
     * @param flag
     * @return
     */
    public static boolean flagCheck(String flag) {
        return "YES".equalsIgnoreCase(flag);
    }

    /**
     * 信贷产品还款方式数组组装
     *
     * @param refundWays
     * @return
     */
    public static String formartRefundWay(String[] refundWays) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < refundWays.length; i++) {
            if (TextUtils.equals(refundWays[i], "ONCE_TIME")) {
                builder.append("到期还本付息/");
            } else if (TextUtils.equals(refundWays[i], "PROFIT_PRINCIPAL")) {
                builder.append("先息后本/");
            } else if (TextUtils.equals(refundWays[i], "MONTH_AMT")) {
                builder.append("等额本息/");
            }
        }
        if (builder.length() > 0) {
            return builder.substring(0, builder.length() - 1);
        } else {
            return "";
        }
    }

    /**
     * 日期格式化
     * yyyy-MM-dd
     */
    public static String formartDate(long time) {
        return HsDateUtils.timeformat(HsDateUtils.farmat_date_3, time);
    }


    public static String formartDate2(long time) {
        return HsDateUtils.timeformat(HsDateUtils.farmat_day_1, time);
    }


    /**
     * 通过身份证获取性别
     *
     * @param certNo
     * @return
     */
    public static String getSexByCertNo(String certNo) {
        char c = certNo.charAt(certNo.length() - 2);
        int parseInt = (int) c - (int) '0';
        if (parseInt % 2 == 0) {
            return "FEMALE";
        } else {
            return "MALE";
        }
    }

    /**
     * 读取配置文件密码是否进行加密
     *
     * @param context
     * @param pass
     * @return
     */
    public static String encodePass(Context context, String pass) {
        if (context.getResources().getBoolean(R.bool.if_md5pass)) {
            return MD5Utils.getMD5String(pass);
        }
        return pass;
    }

    /**
     * 两个String相除（float）（num/num2）
     *
     * @param num1 除数
     * @param num2 被除数
     * @param
     * @return String
     */
    public static String division(String num1, String num2) {
        String result = "0";
        try {
            result = (new BigDecimal(num1).divide(new BigDecimal(num2), 2, BigDecimal.ROUND_DOWN)) + "";
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
        return result;
    }

    /**
     * 天转毫秒
     *
     * @param day
     * @return
     */
    public static long day2ms(int day) {
        return day * 24 * 3600 * 1000;
    }

    /**
     * 获取当前时间精确到秒
     *
     * @return
     */
    public static String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        return str;
    }

    /**
     * 日期转时间戳
     *
     * @return
     */
    public static String date2time(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//24小时制
        //      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));

        long time = 0;
        try {
            time = simpleDateFormat.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time + "";
    }

    /**
     * 拼接json字符串作为参数
     *
     * @param map
     * @return
     */
    public static JSONObject getJSONParams(JSONObject map, String key, String zwgt_data) {
        String zwgt_data_time = Date.parse(zwgt_data) / 1000 + "";
        //body体验签
        String sign = BaseRequestTool2.getSign(zwgt_data, map.toString());
        //需要上传的加密的data
//		Log.e("zwgt_data: " + zwgt_data + " configKey: " + key + " s: " + map.toString() + " zwgt_data_time: " + zwgt_data_time.substring(zwgt_data_time.length() - 8,zwgt_data_time.length()) + " data_time: "+ zwgt_data_time);
//        String data = BaseRequestTool2.getData(zwgt_data, key, map.toString(), zwgt_data_time.substring(zwgt_data_time.length() - 8, zwgt_data_time.length()));
        String data = BaseRequestTool2.getData(zwgt_data, key, map.toString(), zwgt_data_time.substring(zwgt_data_time.length() - 8, zwgt_data_time.length()));

        JSONObject params = new JSONObject();
        try {
            params.put("data", data);
            params.put("sign", sign);
            params.put("timestamp", zwgt_data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    /**
     * 用于验签失败进入登陆页面
     *
     * @param mContext
     */
    public static void goToLogin(Context mContext, Class clazz) {
        BaseAppManager manager = BaseAppManager.getInstance();
        manager.getActivity(clazz).finish();

        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
    }

    public static void goToLogin(Context mContext) {
        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
    }

    public static String moneyOneThousandsFormat(String value) {
        if (value == null) {
            return "0元";
        }

        if (value.isEmpty()) {
            return "0元";
        }

        String money = "0元";
        double formerMoneys = MathUtils.string2double(value);
        double floor;
        double format;
        String format1;
        DecimalFormat formarter1;
        if (formerMoneys >= 10000.0D && formerMoneys < 1.0E8D && (formerMoneys % 10000.0D) == 0) {
            floor = MathUtils.string2double(MathUtils.division(value, "10000"));
            floor = MathUtils.string2double(MathUtils.division(Math.floor(MathUtils.string2double(MathUtils.multiply(new double[]{floor, 100.0D}))), 100.0D));
            format = Math.floor(floor);
            format1 = "###,##0.##";
            if (floor != format) {
                format1 = "###,##0.00";
            }

            formarter1 = new DecimalFormat(format1);
            money = formarter1.format(floor) + "万";
        } else if (formerMoneys >= 1.0E8D && (formerMoneys % 1.0E8D) == 0) {
            floor = MathUtils.string2double(MathUtils.division(value, "100000000"));
            floor = MathUtils.string2double(MathUtils.division(Math.floor(MathUtils.string2double(MathUtils.multiply(new double[]{floor, 100.0D}))), 100.0D));
            format = Math.floor(floor);
            format1 = "###,##0.##";
            if (floor != format) {
                format1 = "###,##0.00";
            }

            formarter1 = new DecimalFormat(format1);
            money = formarter1.format(floor) + "亿";
        } else {
            formerMoneys = Math.floor(formerMoneys * 100.0D) / 100.0D;
            floor = Math.floor(formerMoneys);
            String format2 = "###,##0.##";
            if (formerMoneys != floor) {
                format2 = "###,##0.00";
            }

            DecimalFormat formarter = new DecimalFormat(format2);
            money = formarter.format(formerMoneys) + "元";
        }

        return money;
    }

    public static String moneyOneThousands(String value) {
        if (value == null) {
            return "0元";
        }

        if (value.isEmpty()) {
            return "0元";
        }

        String money = "0元";
        double formerMoneys = MathUtils.string2double(value);
        double floor;
        double format;
        String format1;
        DecimalFormat formarter1;
        if (formerMoneys >= 10000.0D /*&& formerMoneys < 1.0E8D*/) {
            floor = MathUtils.string2double(MathUtils.division(value, "10000"));
            floor = MathUtils.string2double(MathUtils.division(Math.floor(MathUtils.string2double(MathUtils.multiply(new double[]{floor, 100.0D}))), 100.0D));
            format = Math.floor(floor);
            format1 = "###,##0";
            if (floor != format) {
                format1 = "###,##0";
            }

            formarter1 = new DecimalFormat(format1);
            money = formarter1.format(floor) + "万";
        }/* else if(formerMoneys >= 1.0E8D) {
            floor = MathUtils.string2double(MathUtils.division(value, "100000000"));
            floor = MathUtils.string2double(MathUtils.division(Math.floor(MathUtils.string2double(MathUtils.multiply(new double[]{floor, 100.0D}))), 100.0D));
            format = Math.floor(floor);
            format1 = "###,##0.##";
            if(floor != format) {
                format1 = "###,##0.00";
            }

            formarter1 = new DecimalFormat(format1);
            money = formarter1.format(floor) + "亿";
        } */ else {
            formerMoneys = Math.floor(formerMoneys * 100.0D) / 100.0D;
            floor = Math.floor(formerMoneys);
            String format2 = "###,##0.##";
            if (formerMoneys != floor) {
                format2 = "###,##0.00";
            }

            DecimalFormat formarter = new DecimalFormat(format2);
            money = formarter.format(formerMoneys) + "元";
        }

        return money;
    }

    public static String moneyOneThousandsUnit(String money) {
        double formerMoneys = MathUtils.string2double(money);
        String unit = "元";
        if (formerMoneys >= 1.0E8D) {
            unit = "亿";
        } else if (formerMoneys >= 10000.0D && formerMoneys % 10000.0D == 0) {
            unit = "万";
        } else {
            unit = "元";
        }
        return unit;
    }

    /**
     * 判断是否是数字
     *
     * @param value
     * @return
     */
    public static boolean isDouble(String value) {
        try {
            double v = Double.parseDouble(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static boolean isApplicationBroughtToBackground(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param mContext
     * @return
     */
    public static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 处理日期
     *
     * @param term
     * @param start
     * @param end
     * @return
     */
    public static String getTerm(String term, int start, int end) {
        try {
            if (start > end || start < 0) {
                return "";
            }

            if (term == null) {
                return "";
            }

            if (term.length() > end) {
                return term.substring(start, end);
            } else {
                return term;
            }
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取Umeng渠道号
     *
     * @param context
     * @return 渠道号
     */
    public static String getChannel(Context context) {
        String channel = "P1OJDiTB";
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (info != null && info.metaData != null) {
                String metaData = info.metaData.getString("UMENG_CHANNEL");
                if (!TextUtils.isEmpty(metaData)) {
                    channel = metaData;
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channel;
    }

    /**
     * 百分比数值保留两位小数
     *
     * @param
     * @param
     * @return
     */
    public static String formart2(double value) {
        DecimalFormat formater = new DecimalFormat();
        formater.setMaximumFractionDigits(2);
        formater.setMinimumFractionDigits(2);
        formater.setRoundingMode(RoundingMode.FLOOR);
        return formater.format(value).replace(",", "") + "%";
    }

    //判断是否多次点击
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if ( 500 < timeD) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

}
